<?php
error_reporting(1);

$movtypes	= array("mov","avi","mpg","mpeg","divx","ogm","mp4","mkv","m4v","mp4v");	// What are movie file extensions
$startdir	= getcwd();

$getsubs		= true;												// Get subtitles for the movies


	$language = array();
	$data = file(str_replace("getsubtitles.php","srtlanguages.txt",$argv[0]));
	foreach($data as $line){
		$temp = explode("\t",$line);
		$language[trim($temp[2])] = array("series"=>$temp[0],"movies"=>$temp[1]);
	}
	$thelanguage = $language[$argv[3]]["movies"];


if(isset($argv[1])){ // Directory is given
	$subdirname = $argv[1];

	$imdbnr		= 0;
	$filesize	= 0;
	$xml		= array();
	$xmlfile	= false;
	$cover		= false;
	$subtitles	= false;
	$listavi	= array();
	$listavism	= array();
	$sample		= "";
	$trailer	= "";
	$movcount	= 0;
	$xmlcount	= 0;
	$jpgcount	= 0;
	$srtcount	= 0;
	$nfofile	= "";


	$temp	= file($subdirname."/imdbnr.txt");
	$imdbnr	= trim($temp[0]);


		$subdir = opendir($subdirname."/");
		while(false !== ($file = readdir($subdir))){
			if(substr($file,0,1) == "."){ continue; }				// No hidden files / dirs
			$ext = strtolower(substr($file, strrpos($file, ".")+1));
			if($ext == ""){ continue; }
			if(in_array($ext, $movtypes)){							// It is a movie
				$movcount++;
				if(strpos($file, "samp") > 0){						// It is a sample
					$sample = $file;
				}elseif(strpos($file, "trailer") > 0){				// It is a trailer
					$trailer = $file;
				}else{												// It is a part of the movie
					array_push($listavism, substr($file, 0, strrpos($file, ".")));
					array_push($listavi, $file);
					if($filesize == 0){								// Get file size of first movie, for subtitle downloading...
						$filesize = filesize($subdirname."/".$file);
					}
				}
			}elseif(strpos($file, ".xml") > 0){						// It is a xml data file
				$xmlfile = true;
				$xmlcount++;
			}elseif($file == "cover.jpg"){							// It is a (folder) cover
				$cover = true;
			}elseif($ext == "jpg"){									// Other JPG file, consider it to be symlink to cover
				$jpgcount++;
			}elseif(($ext == "srt") or ($ext == "sub")){			// We have subtitles...
				$srtcount++;
				$subtitles = true;
			}elseif($ext == "nfo"){									// We have more info...
				$nfofile = $file;
			}
		}



			if($getsubs and !$subtitles){
				$file = implode("",file("http://www.opensubtitles.org/en/search/subsumcd-".count($listavi)."/sublanguageid-".$thelanguage."/moviebytesize-".$filesize."/imdbid-".$imdbnr."/subformat-srt/xml"));

$dbg = fopen("/tmp/temp.log","a");
fwrite($dbg, "http://www.opensubtitles.org/en/search/subsumcd-".count($listavi)."/sublanguageid-".$thelanguage."/moviebytesize-".$filesize."/imdbid-".$imdbnr."/subformat-srt/xml");
fwrite($dbg,"\n\n");

				$dom = new DomDocument();
				$dom->loadXML($file);
				$subtitles = $dom->getElementsByTagName("subtitle");
				$found = false;
				$maxscores = 0;
				foreach($subtitles as $sub){
					$dl = $sub->getElementsByTagName("SubDownloadsCnt")->item(0)->textContent;
					if($dl > $maxscores){
						$bestshot = $sub;
						$dlsub = $sub;
						$maxscores = $dl;
						$found = true;
					}
				}
				if(!$found){
					$file = implode("",file("http://www.opensubtitles.org/en/search/subsumcd-".count($listavi)."/sublanguageid-".$thelanguage."/imdbid-".$imdbnr."/subformat-srt/xml"));

					$dom = new DomDocument();
					$dom->loadXML($file);
					$subtitles = $dom->getElementsByTagName("subtitle");
					$found = false;
					$maxscores = 0;

					$temp = "";
					if($nfofile != ""){
						$temp = implode("",file($subdirname."/".$nfofile));
					}elseif(file_exists($subdirname."/relname.txt")){
						$temp = implode("",file($subdirname."/relname.txt"));
					}

					foreach($subtitles as $sub){
						$mytemp = $sub->getElementsByTagName("MovieReleaseName");
						foreach($mytemp as $rlnm){
							$relname = $rlnm->textContent;
							if($temp != ""){
								if((strlen($relname) > 2) and (strpos(strtolower($temp), strtolower($relname)))){
									$dl = $sub->getElementsByTagName("SubDownloadsCnt")->item(0)->textContent;
									if($dl > $maxscores){
										$bestshot = $sub;
										$dlsub = $sub;
										$maxscores = $dl;
										$found = true;
									}
								}
							}
						}

						if(!$found){
							$mytemp = $sub->getElementsByTagName("SubAuthorComment");
							foreach($mytemp as $rlnm){
								$relname = $rlnm->textContent;

								if($temp != ""){
									if((strlen($relname) > 2) and (strpos(strtolower($temp), strtolower($relname)))){
										$dl = $sub->getElementsByTagName("SubDownloadsCnt")->item(0)->textContent;
										if($dl > $maxscores){
											$bestshot = $sub;
											$dlsub = $sub;
											$maxscores = $dl;
											$found = true;
										}
									}
								}
							}
						}
						
					}

					
					if(!$found){
						// Go to every found subtitles page and check for filenames...
						// Will be slow...
						foreach($subtitles as $sub){
							$sl = $sub->getElementsByTagName("IDSubtitle");
							
							foreach($sl as $sll){
								$suburl  = $sll->getAttribute("Link");
								$subpage = implode("",file("http://www.opensubtitles.org".$suburl."/xml"));
								$subdom = new DomDocument();
								$subdom->loadXML($subpage);
								$files = $subdom->getElementsByTagName("SubActualCD");

								$sf = array();
								foreach($files as $file){
									array_push($sf, $file->getAttribute("SubFileName"));
								}
								sort($sf);
								sort($listavism);

								foreach($sf as $sfile){
									if(in_array(substr($sfile, 0, strrpos($sfile, ".")), $listavism)){
										$bestshot = $sub;
										$found = true;
										$dlsub = $sub;
									}
								}
							}
						}
					}

				}

				if($found){
					$dll = $dlsub->getElementsByTagName("IDSubtitle");
					foreach($dll as $dls){
						$dl = $dls->getAttribute("DownloadLink");

						$temp = implode("",file("http://www.opensubtitles.org".$dl));
						$h = fopen("/tmp/subtitle.zip","w");
						fwrite($h, $temp);

						$zip = array();
						// exec("unzip -nj '".$_POST["target_dir"]."/".$filenameserver."' -d $datadir$temp",$feedback);
						exec("unzip -nj /tmp/subtitle.zip -x 'subtitles.nfo' -d '".$startdir."/".$subdirname."/'", $zip);
						$temp = array();
						$zip = preg_grep("/\.srt/",$zip);
						$srtfiles = array();
						foreach($zip as $line){
							$matches = array();
							if(preg_match("/.+?\s\/mnt.+\/(.+)/", $line, $matches)){
								array_push($srtfiles, $matches[1]);
							}
						}
					
						sort($srtfiles);
						for($i=0;$i<count($srtfiles);$i++){
							rename($startdir.'/'.$subdirname."/".$srtfiles[$i], $startdir.'/'.$subdirname."/".str_replace(substr($listavi[$i],strrpos($listavi[$i],".")),".srt",$listavi[$i]));
						}
						echo "1";
					}
				}else{
					echo "3";
				}
			}else{
				if($subtitles){ echo "1"; }else{ echo "3"; }
			}
}

?>